import { DirectiveBinding } from 'vue';

// 创建加载遮罩元素的函数
const createLoadingElement = (el: HTMLElement, text: string = '加载中...') => {
  // 检查是否已存在加载元素，避免重复创建
  if (el.querySelector('.loading-mask')) return;

  // 创建遮罩层
  const mask = document.createElement('div');
  mask.className = 'loading-mask';
  mask.style.position = 'absolute';
  mask.style.top = '0';
  mask.style.left = '0';
  mask.style.right = '0';
  mask.style.bottom = '0';
  mask.style.backgroundColor = 'rgba(255, 255, 255, 0.7)';
  mask.style.display = 'flex';
  mask.style.alignItems = 'center';
  mask.style.justifyContent = 'center';
  mask.style.flexDirection = 'column';
  mask.style.zIndex = '999';

  // 创建加载动画
  const spinner = document.createElement('div');
  spinner.className = 'loading-spinner';
  spinner.style.width = '40px';
  spinner.style.height = '40px';
  spinner.style.border = '4px solid #f3f3f3';
  spinner.style.borderTop = '4px solid #3498db';
  spinner.style.borderRadius = '50%';
  spinner.style.animation = 'spin 1s linear infinite';

  // 创建加载文本
  const textElement = document.createElement('div');
  textElement.className = 'loading-text';
  textElement.style.marginTop = '10px';
  textElement.style.color = '#333';
  textElement.textContent = text;

  // 添加动画样式
  const style = document.createElement('style');
  style.textContent = `
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `;

  // 组合元素
  mask.appendChild(spinner);
  mask.appendChild(textElement);
  mask.appendChild(style);
  el.appendChild(mask);
};

// 移除加载遮罩元素
const removeLoadingElement = (el: HTMLElement) => {
  const mask = el.querySelector('.loading-mask');
  if (mask) {
    el.removeChild(mask as Node);
  }
};

// 自定义loading指令
export default {
  // 当指令绑定到元素上时
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // 设置元素为相对定位，使遮罩层能正确定位
    if (window.getComputedStyle(el).position === 'static') {
      el.style.position = 'relative';
    }
    
    // 根据绑定值决定是否显示加载状态
    if (binding.value) {
      createLoadingElement(el, binding.arg || '加载中...');
    }
  },

  // 当绑定值更新时
  updated(el: HTMLElement, binding: DirectiveBinding) {
    // 如果新旧值不同，才执行操作
    if (binding.oldValue !== binding.value) {
      if (binding.value) {
        createLoadingElement(el, binding.arg || '加载中...');
      } else {
        removeLoadingElement(el);
      }
    }
  },

  // 当指令与元素解绑时
  unmounted(el: HTMLElement) {
    removeLoadingElement(el);
  }
};
    